package org.goodsl.mdd;

import java.lang.reflect.Field;
import java.util.ArrayList;

/**
 * Created with IntelliJ IDEA.
 * User: Simon Xiao
 * Date: 12-11-12
 * Time: 下午3:55
 * To change this template use File | Settings | File Templates.
 */
public abstract class Validator<T> {
    private String message;
    public Validator(String message){
        this.message = message;
        if(message!=null && message.length()>3)
            parseParams();

    }

    public String getMessage(){
        if(paramFields!=null){
            String newMessage = message;
            for(Field field : paramFields){
                try{
                    Object value = field.get(this);
                    if(value!=null){
                        String valueStr = value.toString();
                        newMessage = newMessage.replace("{"+field.getName() +"}",valueStr);
                    }
                }catch (Exception e){}
            }

            return newMessage;
        }

        return  message;
    }

    private ArrayList<Field> paramFields;

    //解析消息串中内置的参数 {paramName}
    private void parseParams(){
        int startPos = message.indexOf("{");
        while (startPos>=0 && startPos < message.length()-1){
            int endPos = message.indexOf("}",startPos+1);
            if(endPos>0){
                String paramName = message.substring(startPos+1,endPos);
                try{
                    Field field = this.getClass().getDeclaredField(paramName);
                    if(paramFields ==null)
                        paramFields = new ArrayList<Field>();
                    paramFields.add(field);

                }catch (NoSuchFieldException e){}

                startPos = message.indexOf("{",endPos+1);

            }
        }

    }

    public abstract SingleValidResult<T> verify(T variable);
}
